<?php
namespace App\Admin\Controllers\Inventory;

use App\Models\Basics\SysIArea;
use App\Models\Inventory\Record;
use App\Models\Product\ProductClassify;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class RecordController extends AdminController{

    protected $title = '出入库明细';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'record_no' => null,
        'sku' => null,
        'season' => null,
        'classify_id' => null,
        'area_id' => null,
        'action_type' => null,
        'record_type' => null,
        'user_id' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['record_no'] = $this->filters['record_no'];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['area_id'] = getOptions(SysIArea::options(),$this->filters['area_id']);
        $filtersBlade['action_type'] = getOptions(Record::$_actionType,$this->filters['action_type']);
        $filtersBlade['record_type'] = getOptions(Record::$_recordType,$this->filters['record_type']);
        $filtersBlade['user_id'] = getOptions(User::getAMUserOptions(),$this->filters['user_id']);
        $downloadUrl = '/xqc/inventory/record-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('inventory.record.index', compact('paginator','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
//        $startDate = request('start_date');
//        $endDate = request('end_date');
//        $reportDate = $this->__reportDate($startDate,$endDate);
        $filters = [];
        foreach ($filtersField as $field){
//            if(array_key_exists($field,$reportDate)){
//                $filters[$field] = $reportDate[$field];
//            }else{
                $filters[$field] = request($field);
//            }
        }
        return $filters;
    }

//    private function __reportDate($start,$end){
//        if(is_null($start) && is_null($end)){
//            $time = strtotime("midnight first day of -1 month");
//            $startDate = date('Y-m-d',$time);
//            $endDate = date('Y-m-d');
//        }elseif(!is_null($start) && is_null($end)){
//            $startDate = $start;
//            $endDate = date('Y-m-d');
//        }elseif(is_null($start) && !is_null($end)){
//            $time = strtotime("midnight first day of -1 month",strtotime($end));
//            $startDate = date('Y-m-d',$time);
//            $endDate = $end;
//        }else{
//            $startDate = $start;
//            $endDate = $end;
//        }
//        return ['start_date' => $startDate,'end_date' => $endDate];
//    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = Record::query()->orderBy('id','DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('created_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('created_at','<=',$filter.' 23:59:59');
            }
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
            if($field == 'season'){
                $query->whereHas('sku.classify', function ($query) use($filter){
                    $query->where('season', $filter);
                });
            }
            if(in_array($field,['record_no','area_id','user_id','action_type','record_type'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['记录单号','SKU','季节性','品类','站点','操作类型','记录类型','数量','操作人','操作时间','产品名称'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="出入库明细.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = Record::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
